#coding=utf8
import sys, os
import requests, json

try:
    with open(os.path.join('plugin', 'config', 'tuling.json')) as f: key = json.loads(f.read())['key']
except:
    key = '05ba411481c8cfa61b91124ef7389767' 

key = 'e58c524973c84daa8b18272911d34428'
# key = '05ba411481c8cfa61b91124ef7389767'
print key

def get_response(msg, storageClass = None, userName = None, userid = '100'):
    init ={
        'key':key,
        'info': msg,
        'userid': userid,
    }
    url = 'http://www.tuling123.com/openapi/api'
    r = json.loads(requests.post(url, data = init).text)
    print requests.post(url, data = init)
       
    payloads = {
        'key':key,
        'info': msg,
        'userid': userid,
    }
    try:
        r = json.loads(requests.post(url, data = payloads).text)
    except:
        return
    # print r
    try:
        if not r['code'] in (100000, 200000, 302000, 308000, 313000, 314000): return
        if r['code'] == 100000: # 文本类
            return '\n'.join([r['text'].replace('<br>','\n')])
        elif r['code'] == 200000: # 链接类
            return '\n'.join([r['text'].replace('<br>','\n'), r['url']])
        elif r['code'] == 302000: # 新闻类
            l = [r['text'].replace('<br>','\n')]
            for n in r['list']: l.append('%s - %s'%(n['article'], n['detailurl']))
            return '\n'.join(l)
        elif r['code'] == 308000: # 菜谱类
            l = [r['text'].replace('<br>','\n')]
            for n in r['list']: l.append('%s - %s'%(n['name'], n['detailurl']))
            return '\n'.join(l)
        elif r['code'] == 313000: # 儿歌类
            return '\n'.join([r['text'].replace('<br>','\n')])
        elif r['code'] == 314000: # 诗词类
            return '\n'.join([r['text'].replace('<br>','\n')])
    except Exception, e:
        raise 345345
if __name__ == '__main__':
    # while True:
    print(get_response('你是谁啊？', 'ItChat'))
        # a = raw_input('>').decode(sys.stdin.encoding).encode('utf8')
        # print a
        # print(get_response(a, 'ItChat'))